﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Activities;
using System.Activities.XamlIntegration;
using System.Activities.Tracking;
using MyData.Common;
using System.Data;
using Microsoft.Office.Interop.Excel;

namespace MyData.ExcelAddIn.SampleWorkflow
{
  class SampleActivity : IClientActivity
  {
    public void Run(string workflowPath)
    {
      Cursor.Current = Cursors.WaitCursor;

      AutoResetEvent syncEvent = new AutoResetEvent(false);

      var inputs = new Dictionary<String, Object>
        {
          {"ArgTitle",  Convert.ToString(Globals.ThisAddIn.Application.Names.Item("Title").RefersToRange.Value)},
          {"ArgBody",  Convert.ToString(Globals.ThisAddIn.Application.Names.Item("Body").RefersToRange.Value)},
          {"Handle", System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle}
        };

      Activity wf = (Activity)ActivityXamlServices.Load(workflowPath);

      WorkflowApplication wfApp = new WorkflowApplication(wf, inputs);

      Tracking sampleParticipant = new Tracking
      {
        TrackingProfile = new TrackingProfile()
        {
          Name = "CustomTrackingProfile",
          Queries = 
        {
           new ActivityStateQuery()
          {
              // Subscribe for track records from all activities for all states
              //ActivityName = "*"
              //ActivityStates.Closed
              ActivityName = "*",
              States = { ActivityStates.Closed },

              // Extract workflow variables and arguments as a part of the activity tracking record
              // VariableName = "*" allows for extraction of all variables in the scope
              // of the activity
              Variables = 
              {                                
                  { "*" }
              },
              Arguments = 
              {
                  { "*" }
              }
          }   
        }
        }

      };

      sampleParticipant.ActivityStateTracked += new Tracking.ActivityStateTrackedHandler(sampleParticipant_ActivityStateTracked);
      wfApp.Extensions.Add(sampleParticipant);

      wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs wfe)
      {
        IDictionary<String, Object> output = wfe.Outputs;
        syncEvent.Set();
      };

      wfApp.Aborted = delegate(WorkflowApplicationAbortedEventArgs wfe)
      {
        syncEvent.Set();
      };

      wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs efee)
      {
        return UnhandledExceptionAction.Terminate;
      };

      if (Globals.ThisAddIn.CustomTaskPanes.Count > 0)
      {
        WorkflowActivitiesControl workflowActivities = Globals.ThisAddIn.CustomTaskPanes[0].Control as WorkflowActivitiesControl;
        workflowActivities.objectsTreeView.Nodes.Clear();
      }
      wfApp.Run();

      Cursor.Current = Cursors.Default;
    }

    void sampleParticipant_ActivityStateTracked(object sender, ActivityStateTrackedEventArgs e)
    {
      //Invoke a Treeview method to add all ActivityState names and arguments to Nodes
      if (Globals.ThisAddIn.CustomTaskPanes.Count > 0)
      {
        WorkflowActivitiesControl workflowActivities = Globals.ThisAddIn.CustomTaskPanes[0].Control as WorkflowActivitiesControl;
        workflowActivities.Invoke(new WorkflowActivitiesControl.AddNodeDelegate
          (workflowActivities.AddNode), e.ActivityStateRecord.Activity.Name, e.ActivityStateRecord.Arguments);
      }

      //Filter for Name == "FormattingActivity"
      if (e.ActivityStateRecord.Activity.Name == "FormattingActivity")
      {
        string argColor = (string)e.ActivityStateRecord.Arguments["ArgColor"];
        if (Globals.ThisAddIn.Application.ActiveCell != null)
          Globals.ThisAddIn.Application.ActiveCell.Style = argColor;
      }

      //Sample Excel Event Filter
      if (e.ActivityStateRecord.Activity.Name == "SelectDataTableActivity")
      {
        System.Data.DataTable dt = (System.Data.DataTable)e.ActivityStateRecord.Arguments["DataTable"];

        //Next: Excel Extension Methods
        CellRendering render = new CellRendering();
        render.Fill(dt);
      }
      if (e.ActivityStateRecord.Activity.Name == "DocumentParts")
      {
        if (e.ActivityStateRecord.Arguments.Keys.Contains("ContentParts"))
        {
          Dictionary<string, string> contentParts = (Dictionary<string, string>)e.ActivityStateRecord.Arguments["ContentParts"];
          Worksheet sheet = (Worksheet)Globals.ThisAddIn.Application.ActiveSheet;

          int i = 0;
          foreach (var value in contentParts.Values)
          {
            sheet.Cells[i + 1, 1] = value;
            i++;
          }
        }
      }
    }
  }
}
